package com.f6.weixin.houtai.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.f6.utils.SystemConstans;
import com.f6.weixin.common.vo.SNSUserInfo;
import com.f6.weixin.common.vo.WeiXinOauth2Token;
import com.f6.weixin.utils.WeiXinUtils;
import com.f6.weixin.utils.WeixinAuthUtil;

@Controller
public class WeiXinOauthController {
	private Logger logger = LoggerFactory.getLogger(WeiXinOauthController.class);

	@RequestMapping(value = "oauth", method = RequestMethod.GET)
	public ModelAndView entrance(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		ModelAndView mv = new ModelAndView();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// 拿到code
		String code = request.getParameter("code");
		// 用户同意授权
		if (!"authdeny".equals(code)) {
			// get access_token
			WeiXinOauth2Token weixinOauth2Token = WeixinAuthUtil.getOauth2AccessToken(SystemConstans.APPID, SystemConstans.APPSECRET, code);
			String accessToken = weixinOauth2Token.getAccessToken();
			String openId = weixinOauth2Token.getOpenId();
			SNSUserInfo snsuserinfo = WeiXinUtils.getSNSUser(code, accessToken, openId);
			// request.setAttribute("snsUserInfo", snsuserinfo);
			mv.addObject("snsUserInfo", snsuserinfo);
			mv.setViewName("common/me");
		}

		return mv;

	}

}
